package cocurrent;

import org.junit.Test;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

public class LockSupportTest {
    @Test
    public void test() throws InterruptedException {
        Thread thread = new Thread(() -> {
            System.out.println("start!!!");
            LockSupport.park();
            System.out.println("end!!!");
        });

        thread.start();


        LockSupport.unpark(thread);//unpark可以在park之前调用， 提前调用后，park将不会阻塞
        TimeUnit.SECONDS.sleep(5);


    }

    @Test
    public void test2() throws Exception {
//使用lombda表达式创建一个线程t
        Thread t = new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                System.out.println(i);
                if (i == 5) {
                    //调用LockSupport的park()方法阻塞当前线程t
                    LockSupport.park();
                }
                if (i == 8) {
                    //多次park将导致永久被阻塞，无法被解除
                    LockSupport.park();
                    LockSupport.park();
                }

                try {
//使当前线程t休眠1秒
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        //启动当前线程t
        t.start();
        //唤醒线程t
        LockSupport.unpark(t);
        Thread.sleep(10000);
        LockSupport.unpark(t);
        LockSupport.unpark(t);
        while (true) {

        }
    }
}
